<template>
	<!-- 表单弹窗 -->
	<el-dialog 
		v-model="dialogVisible" 
		title="放款列表"
		class="elDiaLog"
		lock-scroll 
		width="1000px"
		:close-on-click-modal="false" 
		:close-on-press-escape="false"
		 >
		<div v-loading="loading">
			<div class="headCont">
				<el-button @click="handleDo('', 'act_add')"  type="primary" plain><template #icon><i-ep-plus/></template>新增</el-button>
				<el-button @click="handleDo('', 'act_edit')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-edit/></template>修改</el-button>
				<el-button @click="handleDo('', 'act_del')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-delete/></template>删除</el-button>
			</div>
			<el-table ref="dataTableRef" 
					  :data="dataList" 
					  align="left" 
					  tooltip-effect="dark"
					  :show-overflow-tooltip="true" 
					  :scrollbar-always-on="true" border
					  @cell-mouse-enter="rowMouse" 
					  @cell-mouse-leave="menuLineVisible=false"
					  @selection-change="handleSelectionChange">
					<el-table-column type="selection" fixed="left" align="center" width="55" />
					<el-table-column label="ID" align="center" prop="id" width="90"></el-table-column>
					<el-table-column label="放款日期" align="center" prop="loan_date">
						<template #default="scope" >
							<span>{{ scope.row.loan_date }}</span>
							<!-- 行菜单 主体 -->
							<div v-show="rowR.id === scope.row.id && menuLineVisible">
								<ul class="menuLine">
									<li class="menuLine__item">
										<el-button type="primary" class="menuBtn" title="修改" size="small" plain @click="handleDo(scope.row, 'act_edit')"><template #icon><i-ep-edit/></template></el-button>
									</li>
									<li class="menuLine__item">
										<el-button type="danger" class="menuBtn" title="删除" size="small" plain @click="handleDo(scope.row, 'act_del')"><template #icon><i-ep-delete/></template></el-button>
									</li>
								</ul>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="放款金额" align="center" prop="loan_amount"></el-table-column>
					<el-table-column label="余额" align="center" prop="balance"></el-table-column>
					<el-table-column label="贷款总额（协议金额）" align="center" prop="loan_total_amount"></el-table-column>
			</el-table>
			<pagination v-if="total > 0" 
				v-model:total="total" 
				v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" 
				@pagination="handleQuery" /> 
		</div>

		<!--表单-->
		<el-dialog :title="formText" v-model="dialogFormVisible" lock-scroll 
		width="1000px"
		:close-on-click-modal="false" 
		:close-on-press-escape="false" class="list-info">
	
			<div v-if="['act_add','act_edit'].includes(dialogStatus)">
				<el-form ref="dataFormRef" :model="formTemp" :rules="formRules" label-position="right"
					label-width="190px">
				<!-- 	<el-form-item label="贷款总额：" prop="loan_total_amount">
						<el-input v-model="formTemp.loan_total_amount" placeholder="请输入贷款总额" type="text" maxlength="30" />
					</el-form-item> -->
					<el-form-item label="放款金额：" prop="loan_amount">
						<el-input v-model="formTemp.loan_amount" placeholder="请输入放款金额" type="text" maxlength="30" />
					</el-form-item> 
					<!--<el-form-item label="余额：" prop="balance">
						<el-input v-model="formTemp.balance" placeholder="请输入余额" type="text" maxlength="30" />
					</el-form-item> -->
					 <el-form-item label="放款日期：" prop="loan_date">
						 <el-date-picker
								style="width: 100%;"
						        v-model="formTemp.loan_date"
						        type="date"
						        placeholder="请输入放款日期"
						        format="YYYY-MM-DD"
								value-format="YYYY-MM-DD"
						      />
					</el-form-item>
				</el-form>
			</div>
			<div v-if="dialogStatus === 'act_info'">
				<el-descriptions size="default" :column="1" border>
					<!-- <el-descriptions-item label-class-name="labelC1"
						label="贷款总额：">{{formTemp.loan_total_amount}}</el-descriptions-item> -->
					<el-descriptions-item label-class-name="labelC1"
						label="放款金额：">{{formTemp.loan_amount}}</el-descriptions-item>
						<!-- <el-descriptions-item label-class-name="labelC1"
							label="余额：">{{formTemp.balance}}</el-descriptions-item> -->
							<el-descriptions-item label-class-name="labelC1"
								label="放款日期：">{{formTemp.loan_date}}</el-descriptions-item>
				</el-descriptions>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button v-if="['act_add','act_edit'].includes(dialogStatus)" v-no-more-click type="primary"
						@click="doData(dialogStatus)">提 交</el-button>
					<el-button @click="dialogFormVisible = false">关闭</el-button>
				</div>
			</template>
		</el-dialog>
	</el-dialog>
</template>


<script setup lang="ts">
	import { useRoute } from 'vue-router';
	import _ from 'lodash-es'
	
	// 获取接口地址
	import {
		financingLogAdd,
		financingLogEdit,
		financingLogList,
		financingLogInfo,
		financingLogDel
	} from "@/api/financing";

	const emit = defineEmits([ 'initRefreshList']);
	// 表单模型
	const cForm = {
		id:undefined,//企业融资记录id
		// loan_total_amount:"",//	贷款总额
		loan_amount:"",//放款金额
		// balance:"",//余额
		loan_date:""//放款日期
	}
	// 验证规则
	const cRules = {
		// loan_total_amount: [{required: true,message: '请输入贷款总额',trigger: 'blur'}],
		loan_amount: [{required: true,message: '请输入放款金额',trigger: 'blur'}],
		// balance: [{required: true,message: '请输入余额',trigger: 'blur'}],
		loan_date: [{required: true,message: '请选择放款日期',trigger: 'change'}]
	}
	
	// const emit = defineEmits(['update:modelValue', 'initRefreshList']);
	const dialogVisible = ref(false);//表格
	const loading = ref(true);
	const total = ref(0);
	const dataList = ref<any>();
	const multipleSelection =ref<any>([]);
	/*** 搜索窗-字段表 */
	const queryParams = reactive({
		page: 1,
		limit: 20,
		fid:""
	});
	const menuLineVisible =ref(true);
	const rowR = ref<any>({});
	const dataFormRef = ref(ElForm);
	const dialogFormVisible = ref<boolean>(false);//表单
	const dialogStatus = ref<string>(""); // 操作行为 formText
	const formText =ref<string>(""); // 操作窗口标题
	const formTemp = ref<any>(cForm);
	//验证规则
	const formRules = ref<any>(cRules);



	// 行菜单事件
	function rowMouse(row:any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val:any) {
		multipleSelection.value = val
	}
	// 初始表单数据
	function resetTemp() {
		formTemp.value = JSON.parse(JSON.stringify(cForm));
		resetForm();
	}
	// 表单重置
	function resetForm() {
		dataFormRef.value.resetFields()
	}
	//新增或者修改加载load按钮
	function handleShow(row:any,act:string){
		dialogVisible.value = true;
		queryParams.fid = row.id;
		getList();
	}
	
	// 操作
	 function handleDo(row:any, act:string) {
		dialogStatus.value = act
		switch (act) {
			case 'act_add':
				dialogFormVisible.value = true
				formText.value = '新建信息'
				formTemp.value = JSON.parse(JSON.stringify(cForm))
				formRules.value = Object.assign({}, cRules)
				nextTick(()=>{
					setTimeout(()=>{dataFormRef.value.clearValidate();},0)
				})
				break
			case 'act_edit':
				dialogFormVisible.value = true
				formText.value = '修改信息';
				formTemp.value = JSON.parse(JSON.stringify(row || multipleSelection.value[0]));
				nextTick(()=>{
					setTimeout(()=>{dataFormRef.value.clearValidate();},0)
				})
				break
			case 'act_del':
				handleDelete(JSON.parse(JSON.stringify(row || multipleSelection.value[0])))
				break
			default:
				dialogFormVisible.value = true
				formText.value = '查看详情'
				formTemp.value = JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				financingLogInfo({id:formTemp.value.id}).then((res) => {
					formTemp.value = res.data
				}).finally(() => {
					
				})
		}
	}
	// 提交数据
	function doData(act:string) {
		dataFormRef.value.validate((valid:any) => {
			if (valid) {
				const tempData = JSON.parse(JSON.stringify(formTemp.value))
				tempData.fid = queryParams.fid ;
				if (tempData.id === undefined) {
					financingLogAdd(tempData).then((res) => {
						dialogFormVisible.value = false
						ElMessage({ message:'信息添加成功',type:'success'})
						getList()
						resetTemp()
						
						emit('initRefreshList');
					}).finally(() => {
						loading.value = false;
					})
				 } 
				 else {
					 financingLogEdit(tempData.id, tempData).then((res) => {
						const index = dataList.value.findIndex(v => v.id === tempData.id)
						dataList.value.splice(index, 1, tempData)
					 	dialogFormVisible.value = false
					 	ElMessage({ message:'信息修改成功',type:'success'})
						getList()
						resetTemp()
						emit('initRefreshList');
					 }).finally(() => {
					 	loading.value = false;
					 })
				}
			}
		})
	}
	
	// 删除表单内容
	function handleDelete(row:any) {
		const Ids =row.id;
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			loading.value = true;
			financingLogDel({ id: Ids }).then(() => {
					ElMessage.success("删除成功");
					getList()
					resetTemp()
			}).finally(() => (loading.value = false));
		});
	}

	function handleQuery(){
		getList();
	}
	// 获取列表的数据
	function getList(type:string='') {
		loading.value = true
		if (type === 'search') {
			queryParams.page = 1
		}
		financingLogList(queryParams).then((res) => {
			dataList.value = res.data.list
			total.value = res.data.count
		}).finally(() => {
			loading.value = false;
		})
	}
	
	// 操作按钮样式
	function buttonType(val) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	
	
	
	onMounted(() => {});
	defineExpose({
	  handleShow
	});
</script>



